package com.framework.dubbo.producer.file2html;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;

import java.io.*;
import java.nio.charset.Charset;

/**
 * 文本文件预览
 * @author xianggj
 * @Date 2021/6/7 17:19
 **/
public class StringFilePreviewUtil extends AbstractFilePreviewTools {
    @Override
    public String convert2Html(String path) {
        return fileContext2Html(path);
    }

    @Override
    public String convert2Html(InputStream in, String ext) {
        try {
            return fileContext2Html(in);
        } catch (IOException e) {
            e.printStackTrace();
            return "文件读取异常";
        }
    }

    @Override
    public String convert2Str(InputStream in, String ext) {
        byte[] buffer = IoUtil.readBytes(in);
        String encode = FileEncodeUtil.getJavaEncode(buffer);
        InputStream inputStream = new ByteArrayInputStream(buffer);
        return IoUtil.read(inputStream, Charset.forName(encode));
    }

    /**
     * 换行符
     */
    private static final String LINE_BREAK  = "</br>";

    public static String fileContext2Html(String path){
        try (FileInputStream fileInputStream = new FileInputStream(path)) {
            return fileContext2Html(fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "文件读取异常";
    }

    private static String fileContext2Html(InputStream InputStream) throws IOException {
        byte[] buffer = IoUtil.readBytes(InputStream);
        String encode = FileEncodeUtil.getJavaEncode(buffer);
        java.io.InputStream inputStream = new ByteArrayInputStream(buffer);
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName(encode));
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer sbf = new StringBuffer("<html><div>");
        String tempStr;
        while ((tempStr = reader.readLine()) != null) {
            tempStr = StrUtil.replace(tempStr, "&" , "&amp;");
            tempStr = StrUtil.replace(tempStr, " " , "&nbsp;");
            tempStr = StrUtil.replace(tempStr, "\t" , "&nbsp;&nbsp;&nbsp;&nbsp;");
            tempStr = StrUtil.replace(tempStr, "'" , "&quot;");
            tempStr = StrUtil.replace(tempStr, "\"" , "&#39;");
            tempStr = StrUtil.replace(tempStr, "<" , "&lt;");
            tempStr = StrUtil.replace(tempStr, ">" , "&gt;");
            tempStr = StrUtil.replace(tempStr, "\n" , LINE_BREAK);
            sbf.append(tempStr);
            sbf.append(LINE_BREAK);
        }
        reader.close();
        sbf.append("</div></html>");
        return sbf.toString();
    }


    public static void main(String[] args) throws FileNotFoundException {
        File sourceFile = new File("D://acc.txt");
        FileInputStream fis = new FileInputStream(sourceFile);

        System.out.println(new StringFilePreviewUtil().convert2Str(fis, "txt"));
    }
}
